package cn.iocoder.yudao.module.scrm.controller.admin.customer;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.customerrepository.CustomerRepositoryRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.customerrepository.CustomerRepositoryRulePageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.customerrepository.CustomerRepositoryRuleRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.customerrepository.CustomerRepositoryRuleSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.customerrepository.CustomerRepositoryDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.customerrepository.CustomerRepositoryRuleDO;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.service.customer.customerrepository.CustomerRepositoryRuleService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 客户库规则")
@RestController
@RequestMapping("/scrm/customer-repository-rule")
@Validated
public class CustomerRepositoryRuleController {

    @Resource
    private CustomerRepositoryRuleService customerRepositoryRuleService;

    @Resource
    private DeptApi deptApi;



    @PostMapping("/create")
    @Operation(summary = "创建客户库规则")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:create')")
    public CommonResult<Integer> createCustomerRepositoryRule(@Valid @RequestBody CustomerRepositoryRuleSaveReqVO createReqVO) throws JsonProcessingException {
        return success(customerRepositoryRuleService.createCustomerRepositoryRule(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户库规则")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:update')")
    public CommonResult<Boolean> updateCustomerRepositoryRule(@Valid @RequestBody CustomerRepositoryRuleSaveReqVO updateReqVO) {
        customerRepositoryRuleService.updateCustomerRepositoryRule(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户库规则")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:delete')")
    public CommonResult<Boolean> deleteCustomerRepositoryRule(@RequestParam("id") Integer id) {
        customerRepositoryRuleService.deleteCustomerRepositoryRule(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户库规则")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:query')")
    public CommonResult<CustomerRepositoryRuleRespVO> getCustomerRepositoryRule(@RequestParam("id") Integer id) {
        CustomerRepositoryRuleDO customerRepositoryRule = customerRepositoryRuleService.getCustomerRepositoryRule(id);

        return CommonResult.success(buildCustomerRepositoryRuleDetail(customerRepositoryRule));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户库规则分页")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:query')")
    public CommonResult<PageResult<CustomerRepositoryRuleRespVO>> getCustomerRepositoryRulePage(@Valid CustomerRepositoryRulePageReqVO pageReqVO) {
        PageResult<CustomerRepositoryRuleDO> pageResult = customerRepositoryRuleService.getCustomerRepositoryRulePage(pageReqVO);

        // 拼接数据
        return success(new PageResult<>(buildCustomerRepositoryRuleDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    //单个查询的详情
    private CustomerRepositoryRuleRespVO buildCustomerRepositoryRuleDetail(CustomerRepositoryRuleDO customerDO) {
        if (customerDO == null) {
            return null;
        }
        return buildCustomerRepositoryRuleDetailList(Collections.singletonList(customerDO)).get(0);
    }

    //分页的详情
    public List<CustomerRepositoryRuleRespVO> buildCustomerRepositoryRuleDetailList(List<CustomerRepositoryRuleDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 1.1 批量获取所有部门 ID 并查询部门信息
        Set<Long> deptIds = list.stream()
                .flatMap(repositoryDO -> repositoryDO.getDeptIds().stream())
                .collect(Collectors.toSet());
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMapNotCheckDataPermission(deptIds);

        // 2. 转换成 VO
        return BeanUtils.toBean(list, CustomerRepositoryRuleRespVO.class, ruleVO -> {
            // 2.1 设置部门名称列表
            List<String> deptNames = ruleVO.getDeptIds().stream()
                    .map(deptMap::get)
                    .filter(Objects::nonNull) // 过滤掉空值
                    .map(DeptRespDTO::getName)
                    .collect(Collectors.toList());
            ruleVO.setDeptNames(deptNames); // 假设有 setDeptNames 方法
        });
    }



    @GetMapping("/export-excel")
    @Operation(summary = "导出客户库规则 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:customer-repository-rule:export')")
    @OperateLog(type = EXPORT)
    public void exportCustomerRepositoryRuleExcel(@Valid CustomerRepositoryRulePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerRepositoryRuleDO> list = customerRepositoryRuleService.getCustomerRepositoryRulePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "客户库规则.xls", "数据", CustomerRepositoryRuleRespVO.class,
                        BeanUtils.toBean(list, CustomerRepositoryRuleRespVO.class));
    }

}